#include "GameState.h"
#include "SimpleRender.h"
#include "Timer.h"


#define NULL 0 // wow null isn't defined in C++!

GameStateManager::GameStateManager()
{
	Reset();
}

void GameStateManager::Reset()
{
	TheGameState = NULL;
	TheNextGameState = NULL;
}

void GameStateManager::Init()
{
	LastUpdateTime = 0;

	Input::Get().Init();

	// create a D3D window
	SimpleRender::Get().Init();

	if (TheGameState != NULL)
	{
		TheGameState->Init();
	}
	else
	{
		if (TheNextGameState != NULL)
		{
			if(TheGameState)
			{
				TheGameState->Exit();
				delete TheGameState;
			}

			TheGameState = TheNextGameState;
			TheNextGameState = NULL;
		}

		if(TheGameState)
		{
			TheGameState->Init();
		}
	}
}

void GameStateManager::SetGameState(GameState* NewState)
{
	TheNextGameState = NewState;
}

bool GameStateManager::Update()
{
	// update inputs
	GamePadManager::Get().Update(0);
	Input::Get().Process();

	Input::KeyState ESC = Input::Get().GetKeyboard().GetKey(DIK_ESCAPE);

	// quit if backspace is pressed
	if(ESC  == Input::KeyState_Pressed)
		//if(GamePadManager::Get().GetState(0).ButtonsSingle.Back)
	{
		return 0;
	}

	int CurrentTime = Timer::GetTimeMilliSeconds();
	int TimeSinceLastUpdate = CurrentTime - LastUpdateTime;

	// not yet
	if(TimeSinceLastUpdate < 1000/UPDATESPERSECOND)
		return 1;
	else // lets do an update
		LastUpdateTime = CurrentTime;

	if (TheNextGameState != NULL)
	{
		if(TheGameState)
		{
			TheGameState->Exit();
			delete TheGameState;
		}

		TheGameState = TheNextGameState;
		TheNextGameState = NULL;

		TheGameState->Init();
	}


	if (TheGameState == NULL)
	{
		return true;
	}
	return TheGameState->Update();

}

void GameStateManager::Render()
{	
	SimpleRender::Get().ClearScreen(Colour::BLACK);

	SimpleRender::Get().g_pd3dDevice->BeginScene();

	if (TheGameState != NULL)
	{	
		//render gamestate
		TheGameState->Render();
	}

	SimpleRender::Get().g_pd3dDevice->EndScene();

	// Present the backbuffer contents to the display
	SimpleRender::Get().g_pd3dDevice->Present( NULL, NULL, NULL, NULL );


}

void GameStateManager::Exit()
{
	if(TheGameState != NULL)
	{
		TheGameState->Exit();
		delete TheGameState;

		TheGameState = NULL;
	}

	if(TheNextGameState != NULL)
	{
		delete TheNextGameState;

		TheNextGameState = NULL;
	}

	GamePadManager::Kill();
}



GameStateManager* TheGameStateManager::pGameStateManager = NULL;

